package com.sixi.phoneEnc;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class PhoneNumberEncrypt {

	public static void main(String[] args) throws IOException {

		if(args.length == 0 ){
			System.err.println("please spefic the three prefix you want encrypt");
			System.exit(-1);
		}
		
		String threePrefixStr = args[0];
		
		String[] threePrefixSpli = threePrefixStr.split(",");
		
		OutputStream os;
		
		for(String threePrefix : threePrefixSpli){
			
			for(int fourPre = 0; fourPre <=9 ; ++ fourPre){
				String fourPrefix = threePrefix + fourPre;
				File fourPrefixFile = new File("./" + threePrefix + "/" + fourPrefix + "-Encrypt.txt");
				
				os = new FileOutputStream(fourPrefixFile);
				StringBuffer sb = new StringBuffer();
				for(int i = 0; i <= 9999999; ++i){
					String lastSeven = String.format("%07d", i);
					String phoneNumber = fourPrefix +  lastSeven;
					sb.append(phoneNumber).append("\t").append(getMd5(phoneNumber)).append("\n");
				}
				os.write(sb.toString().getBytes());
				os.flush();
				
				System.out.println("Writed File : " + fourPrefixFile.getName());
			}
		}
		
	}

	
	//生成MD5
    public static String getMd5(String inStr) {
            MessageDigest md5 = null;
            try {
                    md5 = MessageDigest.getInstance("MD5");
            } catch (Exception e) {
                    System.out.println(e.toString());
                    e.printStackTrace();
                    return "";
            }
            char[] charArray = inStr.toCharArray();
            byte[] byteArray = new byte[charArray.length];

            for (int i = 0; i < charArray.length; i++) {
                    byteArray[i] = (byte) charArray[i];
            }
            byte[] md5Bytes = md5.digest(byteArray);
            StringBuffer hexValue = new StringBuffer();
            for (int i = 0; i < md5Bytes.length; i++) {
                    int val = ((int) md5Bytes[i]) & 0xff;
                    if (val < 16) {
                            hexValue.append("0");
                    }
                    hexValue.append(Integer.toHexString(val));
            }
            return hexValue.toString();
    }
	
}
